﻿using System.IO;
using System.Net;

namespace CodeContrib.Web
{
	public static class WebRequestExtensions
	{
		public static string HttpPost(this WebRequest webRequest, string data, string charSet, string userAgent)
		{
			var request = (HttpWebRequest)webRequest;
			request.ContentLength = data.Length;
			request.ContentType = "application/x-www-form-urlencoded; charset=" + charSet.AsNullIfEmpty() ?? "UTF-8";
			request.Method = "POST";
			request.UserAgent = userAgent;

			var writer = new StreamWriter(request.GetRequestStream());
			writer.Write(data);
			writer.Close();

			var reader = new StreamReader(request.GetResponse().GetResponseStream());
			var response = reader.ReadToEnd();
			reader.Close();

			return response;
		}
	}
}